package com.gx.smart.building.ui.common.event;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

import com.gx.smart.base.BaseActivityV2;
import com.gx.smart.lib.event.LoadingMessageEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * @author: xiaosy
 * 时间: 2021/12/23
 * @Description: 使用event bus控制loading view的显示
 * @Version: 1.0
 **/
public class LoadingUI implements LifecycleObserver {
    private final BaseActivityV2 activity;
    public LoadingUI(BaseActivityV2 activity) {
        this.activity = activity;
    }

    private void registerEventBus() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    private void unregisterEventBus() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().removeAllStickyEvents();
            EventBus.getDefault().unregister(this);
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    private void startLoading() {
        registerEventBus();
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    private void stopLoading() {
        unregisterEventBus();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void messageEvent(LoadingMessageEvent event) {
        activity.showInitLoadView(event.isLoading());
    }

}
